//
//  BKBaseRequest.m
//  智能备考学习
//
//  Created by 盛超 on 2018/1/18.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "BKBaseRequest.h"

// FTP请求
#import <GoldRaccoon/GRListingRequest.h>
#import <GoldRaccoon/GRRequestsManager.h>


@interface BKBaseRequest() <GRRequestsManagerDelegate>
{
    // FTP回调
    void (^ftpDownloadSuccessBlock)(NSString *unzipPath, NSArray *subPaths);
    void (^ftpDownloadFailureBlock)(NSError *error);
}
@property (nonatomic, strong) GRRequestsManager *requestsManager;

@end

@implementation BKBaseRequest

- (CGFloat)requestTimeoutInterval {
    return 15;
}

- (void)requestGetMethodWithSuccess:(void (^)(id))success Failure:(void (^)(NSError *))failure {
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    configuration.timeoutIntervalForRequest = self.requestTimeoutInterval;
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",  @"application/json", @"text/html", @"text/json", @"text/xml",@"text/javascript", nil];

    NSString *url = [NSString stringWithFormat:@"%@%@",KZGetUserDefaults(SystemIP),self.requestUrl];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//转UTF-8
    
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:url parameters:self.requestParam error:nil];

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@" http response code : %ld",httpResponse.statusCode);

        if (error) {

            [self showErrorHud:error.code];

            failure(error);

        } else {
            success(responseObject);
        }
    }];
    [dataTask resume];
}


- (void)requestPostMethodWithSuccess:(void (^)(id))success Failure:(void (^)(NSError *))failure {
    //1.设置请求路径
    NSString *url = [NSString stringWithFormat:@"%@%@",KZGetUserDefaults(SystemIP),self.requestUrl];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//转UTF-8
    NSURL *URL=[NSURL URLWithString:url];//不需要传递参数
    
    //2.创建请求对象
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
    request.timeoutInterval=self.requestTimeoutInterval;//设置请求超时为5秒
    request.HTTPMethod=@"POST";//设置请求方法
    
    //设置请求头
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    //设置请求体
    NSString *param = [self.requestParam yy_modelToJSONString]; //[NSObject objectToJson:self.requestParam];
    request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
    
    //3.发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
            NSLog(@" http response code : %ld",httpResponse.statusCode);
            
            if (error) {
                
                [self showErrorHud:error.code];
                
                failure(error);
                
            } else {
                
                success(data);
            }
        });
        
    }];
    [dataTask resume];
}

- (void)gr_addRequestForListDirectoryAtPath:(NSString *)path
                                    success:(void(^)(NSString *unzipPath, NSArray *subPaths))success
                                    failure:(void(^)(NSError *error))failure {
    ftpDownloadSuccessBlock = success;
    ftpDownloadFailureBlock = failure;
    [self.requestsManager addRequestForListDirectoryAtPath:path];
    [self.requestsManager startProcessingRequests];
    
}

#pragma mark - GRRequestsManagerDelegate
// 代理方法，每次执行列表方法都会走这个方法
- (void)requestsManager:(id<GRRequestsManagerProtocol>)requestsManager didCompleteListingRequest:(id<GRRequestProtocol>)request listing:(NSArray *)listing {
    
    //沙盒目录
    NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    GRListingRequest *req = (GRListingRequest *)request;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [listing enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *fileName = obj;
        if ([fileName hasSuffix:@"atxz"]) {
            if ([fileName containsString:@"Q20180712093611950"]) {
                
                // 要先在沙盒中创建和服务器文件夹目录一样的文件夹，否则会报错 code:512
                NSString *servicePath = [documentsDirectoryPath stringByAppendingString:[NSString stringWithFormat:@"%@",req.path]];
                if (![fileManager fileExistsAtPath:servicePath]) {
                    [fileManager createDirectoryAtPath:servicePath withIntermediateDirectories:YES attributes:nil error:nil];
                }
                NSString *remotePath = [NSString stringWithFormat:@"%@%@",req.path, fileName];
                NSString *localPath = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",req.path, fileName]];
                [self.requestsManager addRequestForDownloadFileAtRemotePath:remotePath toLocalPath:localPath];
                [self.requestsManager startProcessingRequests];
            }
        }
    }];
}
- (void)requestsManager:(id<GRRequestsManagerProtocol>)requestsManager didFailRequest:(id<GRRequestProtocol>)request withError:(NSError *)error
{
    if (ftpDownloadFailureBlock) {
        ftpDownloadFailureBlock(error);
    }
}
- (void)requestsManager:(id<GRRequestsManagerProtocol>)requestsManager didFailWritingFileAtPath:(NSString *)path forRequest:(id<GRDataExchangeRequestProtocol>)request error:(NSError *)error{
    if (ftpDownloadFailureBlock) {
        ftpDownloadFailureBlock(error);
    }
}
- (void)requestsManager:(id<GRRequestsManagerProtocol>)requestsManager didCompleteDownloadRequest:(id<GRDataExchangeRequestProtocol>)request {
    
    
    NSString *zipPath = [[self sandboxDocumentCacheZipsDircetoryPath] stringByAppendingPathComponent:@"Q20180712093611950.zip"];
    [self decodeWithSourcePath:request.localFilePath zipPath:zipPath];
    
    NSString *unzipPath = [[self sandboxDocumentCacheZipsDircetoryPath] stringByAppendingPathComponent:@"Q20180712093611950"];
    
//    [SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath overwrite:YES password:@"" progressHandler:^(NSString * _Nonnull entry, unz_file_info zipInfo, long entryNumber, long total) {
//
//    } completionHandler:^(NSString * _Nonnull path, BOOL succeeded, NSError * _Nullable error) {
//
//        if (succeeded) {
//
//            NSMutableArray *temp = [NSMutableArray new];
//            NSArray<NSString *> *subPaths = [[NSFileManager defaultManager] subpathsAtPath:unzipPath];
//            for (NSString *subPath in subPaths) {
//                NSLog(@"!!!%@", subPath);
//                [temp addObject:[NSString stringWithFormat:@"%@/%@", unzipPath, subPath]];
//            }
//
//            if (ftpDownloadSuccessBlock) {
//                ftpDownloadSuccessBlock(unzipPath, temp.copy);
//            }
//        }
//
//    }];
}


#pragma mark - 辅助
- (void)showErrorHud:(NSInteger)errorcode {
//    dispatch_async(dispatch_get_main_queue(), ^{
//
//        UIWindow *window = [UIApplication sharedApplication].keyWindow;
//
//        [MBProgressHUD showErrorStyleToView:window withCode:errorcode];
//
//    });
  
}

// 获取沙盒路径下缓存zip文件的路径地址
- (NSString *)sandboxDocumentCacheZipsDircetoryPath {
    
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *pathName = [documents stringByAppendingString:@"/cache_zips"];
    
    if ([fm fileExistsAtPath:pathName]) {
        return pathName;
    } else {
        [fm createDirectoryAtPath:pathName withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return pathName;
}

// 解密代码
- (void)decodeWithSourcePath:(NSString*)path zipPath:(NSString*)zipPath {
    //encryptStr-秘钥 path-文件路径 zipPath-解密后压缩包路径
    //秘钥d91077b590a545d296783e1375317670
    //获取key长度
    NSString *encryptStr = @"d91077b590a545d296783e1375317670";
    NSInteger length = encryptStr.length;
    NSInteger bufferSize = length*32*8;
    //转换c字符串
    const char *keys = [encryptStr cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned char cKey[length];
    memcpy(cKey, keys, length);
    //数据初始化，空间未分配 配合使用 appendBytes
    NSMutableData *encryptData = [[NSMutableData alloc] initWithCapacity:bufferSize];
    // 获取字节指针
    NSData *data = [NSData dataWithContentsOfFile:path];
    const Byte *point = data.bytes;
    for (int i = 0; i < data.length; i++) {
        int l = i % length;
        // 算出当前位置字节，要和密钥的异或运算的密钥字节
        char c = cKey[l];
        Byte b = (Byte) ((point[i]) ^ c);
        // 异或运算
        [encryptData appendBytes:&b length:1];// 追加字节
    }
    
    // 转成zip到指定目录下
    [encryptData.copy writeToFile:zipPath atomically:YES];
}

#pragma mark - 懒加载
- (GRRequestsManager *)requestsManager{
    if (!_requestsManager) {
        _requestsManager = [[GRRequestsManager alloc] initWithHostname:@"ftp://172.16.41.251:8243" user:@"LangeFtpUser" password:@"LangeFtpPwd*_!"];
        // 设置代理
        _requestsManager.delegate = self;
    }
    return _requestsManager;
}




@end
